'use strict';

import {
  appConst,
  appData,
  appMain,
  appSession,
  appUtils,
} from './lib/instances';

let appActions = {
  '新增': (holder) => {
    handlers.RecordLaunch(holder)
  },
  '修改': (holder) => {
    handlers.RecordLaunch(holder)
  },
  '追加': (holder) => {
    handlers.RecordLaunch(holder)
  },
  '删除': (holder) => {
    handlers.RecordRemoveLaunch(holder)
  },
  '浏览': (holder) => {
    handlers.RecordExploreRange(holder)
  },
  '结束': (holder) => {
    appSession.set('action', '');
    holder.setTts({
      tts: appMain.getTtsStr('记录结束。')
    });
    appMain._stage = appConst.STAGEDONE;
  }
}

let handlers = {
  'ROKID.INTENT.WELCOME': (holder) => {
    appMain.addTtsStr(appConst.tpls.welcome);
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    holder.setPickup({
      enable: true,
      durationInMilliseconds: 6000,
      retryTts: '请重试'
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'Help': (holder) => {
    appMain.addTtsStr(appConst.tpls.help);
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordLaunch': (holder) => { // 记录引导
    let action = '记录';
    if (appSession.get('action') &&
      Rokid.param.request.content.sentence.indexOf('记一下') < 0) {
      action = appSession.get('action');
    }
    holder.setTts({
      tts: appMain.getTtsStr(appConst.tpls.pleaseSay.format({
        'action': action
      }))
    });
    holder.setConfirm({
      confirmIntent: 'RecordDo',
      confirmSlot: 'content',
      retryTts: appConst.tpls.retryTips
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordDo': (holder) => { // 记录操作, 附带处理action
    let content = Rokid.param.request.content.slots.content;
    let record = appSession.get('record_previous');
    let action = appSession.get('action');
    console.debug('[RecordDoAction]', action);
    if (action === '修改' && record !== null) {
      record.content = content;
      record = appData.setRecordNormal(record);
    } else if (action === '追加' && record !== null) {
      record.content += content;
      record = appData.setRecordNormal(record);
    } else {
      action = '记录';
      appSession.set('action', action);
      record = appData.addRecordNormal(content);
    }
    console.debug('[RecordDoItem]', JSON.stringify(record));
    appSession.set('action', '');
    appSession.set('record_previous', record);
    appMain.setTtsStr(appConst.tpls.recordContinue.format({
      action: action,
      content: record.content
    }))
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    let acts = Object.keys(appActions);
    holder.setConfirm({
      confirmIntent: 'RecordAction',
      confirmSlot: 'action',
      optionWords: acts,
      retryTts: appConst.tpls.retryWithActionTips.format({
        'action': acts.join('、')
      })
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordAction': (holder) => { // 选择动作,可以考虑作为内部意图路由
    // 新增 | 修改 | 追加 | 删除 | 浏览 | 结束
    let isOK = true;
    let action = Rokid.param.request.content.slots.action;
    appSession.set('action', action);
    if (['修改', '追加', '删除'].contains(action)) {
      let record = appSession.get('record_previous');
      if (record === undefined || record === null) {
        appMain.setTtsStr('你还没有选定相关记录。');
        isOK = false;
      }
    }

    if (isOK) {
      if (appActions.hasOwnProperty(action)) {
        appActions[action](holder);
      } else {
        appActions['结束'](holder);
      }
    } else {
      holder.setTts({
        tts: appMain.getTtsStr()
      });
    }
  },
  'RecordRemoveLaunch': (holder) => { // 删除记录
    holder.setTts({
      tts: appMain.getTtsStr(appConst.tpls.actionConfirm.format({
        action: '删除'
      }))
    });
    holder.setConfirm(appMain.YON('RecordRemoveDo'));
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordRemoveDo': (holder) => { // 删除记录
    switch (Rokid.param.request.content.slots.yes_or_no) {
      case '是的':
        let record = appSession.get('record_previous');
        if (record !== null) {
          appData.delRecord(record.id);
        }
        appMain.setTtsStr(appConst.tpls.actionOK.format({
          action: '删除'
        }));
        break;
      default:
        appMain.setTtsStr(appConst.tpls.actionCancle.format({
          action: '删除'
        }));
        break;
    }
    appSession.set('action', '');
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordExploreSummary': (holder) => { // 查询记录统计
    let day = Rokid.param.request.content.slots.day;
    if (day === null || day === undefined) {
      day = '总共';
    }
    // 检索数据
    appMain.setTtsStr(appData.exploreRange(day));
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordExploreRange': (holder) => { // 查阅记录范围带summary
    appMain.setTtsStr(appData.summary());
    appMain.setTtsStr(appConst.tpls.exploreSpeakRange);
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    holder.setConfirm({
      confirmIntent: 'RecordExploreSummary',
      confirmSlot: 'day',
      retryTts: '你可查询范围为：今天、昨天、前天、这个星期等，请重试'
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordExploreDo': (holder) => { // 查阅记录
    let direction = Rokid.param.request.content.slots.explore_direction;
    let offset = Rokid.param.request.content.slots.explore_offset;
    offset = JSON.parse(offset).number;
    offset = Math.ceil(offset);
    if (direction === '前' || direction === '上') offset = -offset;
    let record = appData.exploreRecord(offset);
    console.debug('[RecordExploreDo]', JSON.stringify(record));
    if (record !== null && record !== undefined) {
      appMain.setTtsStr(appConst.tpls.exploreRecord.format({
        'date': (new Date(record.create_time)).format('YYYY年MM月DD日 HH时mm分ss秒'),
        'content': record.content
      }));
    } else {
      appMain.setTtsStr('记录暂未查询到！');
    }
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordExploreAction': (holder) => { // 选择动作,可以考虑作为内部意图路由
    let action = Rokid.param.request.content.slots.action;
    appSession.set('action', action);
    if (appActions.hasOwnProperty(action)) {
      appActions[action](holder);
    } else {
      appActions['结束'](holder);
    }
  },
  'RecordClearUpLaunch': (holder) => { // 清空记录
    holder.setTts({
      tts: appMain.getTtsStr(appConst.tpls.actionConfirm.format({
        action: '清空'
      }))
    });
    holder.setConfirm(appMain.YON('RecordClearUpDo'));
    appMain._stage = appConst.STAGEDONE;
  },
  'RecordClearUpDo': (holder) => { // 清空记录
    switch (Rokid.param.request.content.slots.yes_or_no) {
      case '是的':
        appData.clearUpItems();
        appMain.setTtsStr(appConst.tpls.actionOK.format({
          action: '清空'
        }));
        break;
      default:
        appMain.setTtsStr(appConst.tpls.actionCancle.format({
          action: '清空'
        }));
        break;
    }
    holder.setTts({
      tts: appMain.getTtsStr()
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'ROKID.INTENT.EXIT': function (holder) {
    holder.setTts({
      tts: appConst.tpls.existSkillOK
    });
    appMain._stage = appConst.STAGEDONE;
  },
  'Test': function (holder) {
    let action = Rokid.param.request.content.slots.action;
    appSession.set('action', action);
    console.debug('[TestAction]', action);
    let infoArr = Rokid.param.request.content.sentence.split(action);
    if (infoArr.length >= 1) {
      Rokid.param.request.content.slots.content = infoArr[1];
    }
    // 清空记录
    // appData.clearUpItems();
    // 防止重走 AppMain.go 流程的测试代码
    // holder.emit('RecordDo');
    handlers.RecordDo(holder);
  }
}

// 响应事件注册
exports.handler = function (event, context, callback) {
  appMain.init(event, context, callback);
  appMain.registerHandlers(handlers);
  appMain.execute();
};
